package com.cml.rpc.server;

import com.cml.rpc.common.RpcRequest;
import com.cml.rpc.common.RpcResponse;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.EventExecutorGroup;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author cml
 * @create 2021/7/21 13:43
 */
public class NettyRpcServerHandler extends SimpleChannelInboundHandler<RpcRequest> {
    private ServiceProvider serviceProvider;

    public NettyRpcServerHandler(ServiceProvider serviceProvider) {
        this.serviceProvider = serviceProvider;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcRequest rpcRequest) throws Exception {
        System.out.println("接收到客户端请求：" + rpcRequest);
        // 处理请求
        RpcResponse rpcResponse = HandlerRequest(rpcRequest);
        // 发送响应
        channelHandlerContext.writeAndFlush(rpcResponse);
        System.out.println("响应客户端内容：" + rpcResponse);
        System.out.println("----------------");
        channelHandlerContext.close();

    }

    private RpcResponse HandlerRequest(RpcRequest rpcRequest) {
        // 得到服务名称
        String interfaceName = rpcRequest.getInterfaceName();
        // 得到服务具体的实现类
        Object service = serviceProvider.get(interfaceName);
        try {
            // 反射调用方法
            Method method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());
            Object invoke = method.invoke(service, rpcRequest.getParams());
            return RpcResponse.success(invoke);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
            return RpcResponse.fail();
        }
    }
}
